package com.anysoft.user;

import android.content.Intent;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.anysoft.HostConstant;
import com.anysoft.R;
import com.anysoft.base.BaseActivity;
import com.anysoft.bean.BaseBean;
import com.anysoft.event.RegisterEvent;
import com.anysoft.event.RegisterSuccessEvent;
import com.anysoft.utils.CommonUtil;
import com.anysoft.utils.HttpUtils;
import com.anysoft.utils.StringUtils;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 找回密码条件符合 输入新密码
 */
public class RetrievePwdEditActivity extends BaseActivity {

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.leftButton)
    Button leftButton;

    @BindView(R.id.et_new_pwd)
    EditText et_new_pwd;
    @BindView(R.id.et_confirm_pwd)
    EditText et_confirm_pwd;
    @BindView(R.id.iv_pwd_show)
    ImageView iv_pwd_show;

    @BindView(R.id.btn_confirm_edit)
    Button btn_confirm_edit;
    private RegisterEvent retrievePwdEvent;
    private boolean isShowPwd = false;
    /**
     * 新输入的密码是否合规
     */
    private boolean newPwdIsCompliance = false;
    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrieve_pwd_edit);
        ButterKnife.bind(this);
        intent = new Intent();
        title.setText("找回密码");
        retrievePwdEvent = (RegisterEvent) getIntent().getSerializableExtra("retrievePwdEvent");
        et_new_pwd.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                newPwdIsCompliance = false;
                if (!hasFocus) {

                    String new_pwd = et_new_pwd.getText().toString().trim();//新密码
                    if (!StringUtils.isNullOrEmpty(new_pwd)) {
                        checkPassword();
                    }
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @OnClick({R.id.leftButton, R.id.btn_confirm_edit, R.id.iv_pwd_show})
    public void onClick(View view) {
        if (!isFastDoubleClick()) {
            collapseSoftInputMethod(view.getWindowToken());
            switch (view.getId()) {
                case R.id.leftButton:
                    finish();
                    break;
                case R.id.btn_confirm_edit:
                    save();
                    break;
                case R.id.iv_pwd_show:
                    String pwd = et_new_pwd.getText().toString();
                    String pwdAgain = et_confirm_pwd.getText().toString();
                    if (isShowPwd) {
                        et_new_pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                        et_confirm_pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                        isShowPwd = false;
                        iv_pwd_show.setBackgroundResource(R.mipmap.icon_eye_close);
                    } else {
                        et_new_pwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                        et_confirm_pwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                        isShowPwd = true;
                        iv_pwd_show.setBackgroundResource(R.mipmap.icon_eye);
                    }
                    et_new_pwd.setSelection(pwd.length());
                    et_confirm_pwd.setSelection(pwdAgain.length());
                    break;
            }
        }
    }

    private void save() {
        if (!dataCheck()) {
            return;
        }
        resetPassword();
    }

    private boolean dataCheck() {

        String new_pwd = et_new_pwd.getText().toString().trim();//新密码
        String confirm_pwd = et_confirm_pwd.getText().toString().trim();//q确认新密码
        if (new_pwd == null || "".equals(new_pwd)) {
            showErrorMsg("请输入新密码");
            return false;
        }
        if (confirm_pwd == null || "".equals(confirm_pwd)) {
            showErrorMsg("请输入确认密码");
            return false;
        }
        if (!new_pwd.equals(confirm_pwd)) {
            showErrorMsg("新密码与确认密码不同");
            return false;

        }
        if (!newPwdIsCompliance) {
            showErrorMsg("请输入合规密码");
            return false;
        }
        return true;
    }

    /**
     * 密码：至少包含大小写字母及数字中的两种
     * 是否包含
     *
     * @param str
     * @return
     */
    public static boolean isLetterDigit(String str) {
        boolean isDigit = false;//定义一个boolean值，用来表示是否包含数字
        boolean isLetter = false;//定义一个boolean值，用来表示是否包含字母
        for (int i = 0; i < str.length(); i++) {
            if (Character.isDigit(str.charAt(i))) {   //用char包装类中的判断数字的方法判断每一个字符
                isDigit = true;
            } else if (Character.isLetter(str.charAt(i))) {  //用char包装类中的判断字母的方法判断每一个字符
                isLetter = true;
            }
        }
        String regex = "^[a-zA-Z0-9]+$";
        boolean isRight = isDigit && isLetter && str.matches(regex);
        return isRight;
    }


    /**
     * 校验密码是否合规
     */
    private void checkPassword() {
        Map<String, String> params = new HashMap<>();

        String newPwd = et_new_pwd.getText().toString().trim();//新密码
        retrievePwdEvent.setPassword(newPwd);
        params.put("type", "2");//类型
        params.put("certificateNo", retrievePwdEvent.getIdentityNo());//证件号码
        params.put("password", newPwd);//新密码

        OkGo.<String>post(HostConstant.CHECK_PASSWORD)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseJson_CheckPwd(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    /**
     * 重置密码
     */
    private void resetPassword() {
        Map<String, String> params = new HashMap<>();

        String newPwd = et_new_pwd.getText().toString().trim();//新密码
        if (!et_new_pwd.getText().toString().equals(retrievePwdEvent.getPassword())) {
            showConfirmAlert(mActivity, "您修改了密码，请重新输入");
            retrievePwdEvent.setPassword("");
            return;
        }
        params.put("bankCode", retrievePwdEvent.getBankCode());//银行代码
        params.put("bankAccountNo", retrievePwdEvent.getBankAccountNo());//银行账号
        params.put("certificateType", retrievePwdEvent.getIdentityType());//证件类型
        params.put("certificateNo", retrievePwdEvent.getIdentityNo());//证件号码
        params.put("newPassword", newPwd);//新密码
        params.put("authApplyNo", retrievePwdEvent.getAuthApplyNo());//鉴权单号
        params.put("trustChannelId", retrievePwdEvent.getTrustChannelId());//渠道号
        params.put("name", retrievePwdEvent.getUsername());//
        params.put("mobilePhone", retrievePwdEvent.getMobilePhone());//

        OkGo.<String>post(HostConstant.RESET_PASSWORD)
                .tag(this)
                .params(HttpUtils.getCommonParams(this, params))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseJson(response.body());
                    }


                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        showToast("网络加载失败，请稍后再试!");
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                });
    }

    /**
     * 解析校验密码是否合规接口返回的数据
     *
     * @param response
     */
    private void parseJson_CheckPwd(String response) {
        BaseBean bean;
        try {
            bean = new Gson().fromJson(response, BaseBean.class);
        } catch (Exception exception) {
            showConfirmAlert(this, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(this, bean, response)) {
            return;
        }
        newPwdIsCompliance = true;
    }

    /**
     * 解析重置密码接口返回的数据
     *
     * @param response
     */
    private void parseJson(String response) {
        BaseBean bean;
        try {
            bean = new Gson().fromJson(response, BaseBean.class);
        } catch (Exception exception) {
            showConfirmAlert(this, "提示", "数据解析错误");
            return;
        }

        if (!CommonUtil.checkState(this, bean, response)) {
            return;
        }
//        intent.putExtra("back_type", "2");
//        setResult(HostConstant.PWD_BACK,intent);
        EventBus.getDefault().post(new RegisterSuccessEvent(true));
        showToast("密码重置成功");
        finish();
    }

    private void showErrorMsg(String msg) {
        if (msg == null) {
            return;
        }
        showConfirmAlert(mActivity, msg + "");
    }
}
